/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.Group;
import edu.cmu.fithub.db.bean.GroupMembers;
import edu.cmu.fithub.db.bean.User;

public class LeaveGroupAction extends Action {

	public LeaveGroupAction() {
	}

	public String getName() {
		return "leaveGroup.do";
	}

	public String perform(HttpServletRequest request) {

		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);

		try {
			User user = (User) request.getSession().getAttribute("user");
			String groupId = request.getParameter("groupId");
			Session dbSession = DBHelper.getSessionFactory().openSession();
			List<Group> groupList = dbSession.createCriteria(Group.class)
					.add(Restrictions.eq("groupId", Integer.parseInt(groupId)))
					.list();
			if (groupList.size() != 0) {
				List<GroupMembers> groupMembers = dbSession
						.createCriteria(GroupMembers.class)
						.add(Restrictions.eq("group", groupList.get(0)))
						.add(Restrictions.eq("userId", user.getUserId()))
						.list();
				if (groupMembers.size() != 0) {
					dbSession.beginTransaction();
					dbSession.delete(groupMembers.get(0));
					dbSession.getTransaction().commit();
				} else {
					// TODO Handle error: You are not member of this group
				}
			} else {
				// TODO Handle error: No group with such group Id exists
			}

			return "redirectToHome.jsp";

		} catch (NumberFormatException e) {
			errors.add(e.toString());
			return "error.jsp";
		}
	}
}
